package cn.nr19.jian.`object`

import cn.nr19.jian.J2Utils
import cn.nr19.jian.Jian
import cn.nr19.jian.exception.ParserException
import cn.nr19.jian.token.J2Node
import cn.nr19.jian.token.NFunNode

/**
 * 基础简数据类
 */
open class JianLei : JianLeiApi {

    // 变量、功能、事件
    protected val vars = HashMap<String,Any>()
    override fun vars() : Map<String,Any> = vars
    override fun curLeiVars(): HashMap<String, Any> = vars
    val funs = ArrayList<NFunNode>()
    override fun funs(): List<NFunNode> = funs
    val listener = HashMap<String,J2Node>() // 听众
    override fun events(): Map<String, J2Node> = listener

    var datas = HashMap<String,Any>()
    override fun setConf(key: String, value: Any) {
        datas.set(key,value)
    }
    override fun getConf(key: String): Any? {
        return datas[key]
    }

    // 引用功能类 如视图类，系统级别类。 简不支持静态类。M 本身属于变量
    protected val importFunctionObjects = HashMap<String,String>()

    override fun addListener(name: String, j2: J2Node) {
        listener.put(name,j2)
    }



    override fun toString(): String {
        StringBuilder().apply {
            append("变量_${vars.size}:")
            for (key in vars.keys) {
                append(key).append(",")
            }
            append("\n")



            append("功能_").append(funs.size).append(":")
            funs.forEach {
                append(it.name).append(",")
            }
            append("\n")


            append("事件_").append(listener.size).append(":")
            listener.forEach {
                append(it.key).append(",")
            }
            append("\n\n")

            return toString()
        }
    }
    override fun getFun(name : String, pars: List<Any>): NFunNode? {
        for (nf in funs) {
            // 功能数量一致即可
            if (nf.pars.size == pars.size && nf.name == name) return nf
        }
        return null
    }


    override fun getEvent(name: String, parsSize : Int): J2Node? {
        return listener.get(name)
    }

    override fun getVar(key: String): Any? {
        return vars[key]
    }
    override fun createVar(name: String, value: Any) {
        vars[name] = value
    }
    override fun setVar(name: String, value: Any) {
        if (vars.containsKey(name)) vars.set(name,value)
        else throw ParserException("未定义变量 ${name}",0)
    }
    override fun addFun(f: NFunNode) {
        funs.add(f)
    }


    override fun addImport(name: String, path: String) {
        importFunctionObjects.set(name,path)
    }
}